package com.bookmanager.www.controller.wxpay;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bookmanager.www.common.Constants.PreferentialConstant;
import com.bookmanager.www.common.DTO.WxCreateOrderDTO;
import com.bookmanager.www.common.utils.OffersAndRatingsUtils;
import com.bookmanager.www.common.utils.Result;
import com.bookmanager.www.entity.FlBookOrder;
import com.bookmanager.www.entity.FlPayinfo;
import com.bookmanager.www.mapper.FlBookorderMapper;
import com.bookmanager.www.mapper.FlUserMapper;
import com.bookmanager.www.service.FlPayinfoService;
import com.ijpay.alipay.AliPayApi;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: 风离
 * @Date: 2021/11/03/22:41
 * @Description:
 */
@RestController
@RequestMapping("/wxPay")
@Api(tags = "微信支付测试")
@Slf4j
public class WxPayController {
    @Resource
    FlBookorderMapper flBookorderMapper;
    @Resource
    FlUserMapper flUserMapper;
    @Resource
    FlPayinfoService flPayinfoService;


    @PostMapping("/createOrder")
    @ApiOperation(value = "微信支付发起")
    /**
     * 微信支付流程
     * 1 传入orderId 首先验证orderId是否存在本地数据库中 不存在返回错误信息 存在继续判断该订单是否已支付
     * 2 有该订单就修改支付类型为微信支付（最开始都默认支付宝支付）
     * 3 把订单信息封装好 并生成微信收款码url返回给前端
     */

    public Result sendPostPay(@RequestParam("orderId")String orderId)
    {
        //1
        FlBookOrder flBookOrder = flBookorderMapper.selectOrderByOrderId(orderId);
        if(flBookOrder==null)
        {
            return Result.fail("该订单编号不存在！！创建订单失败","");
        }else if(flBookOrder.getStatus()!=0)
        {
            return Result.fail("该订单已付款无需重复付款！！！","");
        }
        //2
        int updated = flBookorderMapper.updatePaymentTypeByOrderId(orderId,0);
        System.out.println("订单支付类型是否改为微信支付了？？"+((updated!=0)?"是":"否"));
        // 3
        WxCreateOrderDTO orderDTO =new WxCreateOrderDTO();
        orderDTO.setOrder_id(orderId);
        //这里设置实际支付金额
        orderDTO.setOrder_price("0.09");
        String sign = SecureUtil.md5(SecureUtil.md5(orderDTO.getOrder_id()+orderDTO.getOrder_price())+"fl1906");
//        System.out.println(sign);
        orderDTO.setSign(sign);
        orderDTO.setOrder_name("微信支付测试");
        orderDTO.setExtension(flBookOrder.getPayment().toString());
        orderDTO.setRedirect_url("http://a.fl1906.xyz/wxPay/test");
        orderDTO.setOrder_type("wechat");
        System.out.println("orderDTO"+orderDTO.toString());
        //传入对象转JSON
        JSONObject orderJSON = JSONUtil.parseObj(orderDTO, false);
//        System.err.println(HttpUtil.post("http://106.14.154.114:7001/api/order", orderJSON));
        String response = HttpUtil.post("http://106.14.154.114:7001/api/order", orderJSON);
        JSONObject result = JSONUtil.parseObj(response);
        String qrUrl = result.getStr("qr_url");

        String sign2= SecureUtil.md5(SecureUtil.md5(orderDTO.getOrder_price()+"wechat")+"fl1906");
        System.out.println(sign2);

        return Result.succ("订单创建完成 返回微信支付二维码",qrUrl);

//        "http://106.14.154.114:7001/addons/pay/api/notify?desc={{content}}&type=wechat"
    }


    /**
     * 直接调用这个接口默认不会成功
     * @param request
     */
    @GetMapping("/test")
    public void testGet(HttpServletRequest request)
    {
        System.out.println("订单已经支付成功了 可以在这里写业务逻辑了！！！");
        System.out.println("request:"+request);
        if(request!=null)
        {
            Double invoice_amount2 = Double.parseDouble(request.getParameter("extension"));
            String orderId = request.getParameter("order_id");
            FlBookOrder flBookOrder = flBookorderMapper.selectOrderByOrderId(orderId);
            if(flBookOrder!=null)
            {
                System.out.println("certNotifyUrl 验证成功success");
                //更新订单支付时间
                int update3 = flBookorderMapper.updatePaymentTime(orderId, LocalDateTime.now());
                log.info(orderId+"是否更新订单付款时间？"+(update3==1?"是":"否"));
                String flag="余额充值";

                if(flBookOrder.getAddressId().equals(flag))
                {
                    //充值加赠
//                    double add = 1.1;
                    String userId = flBookorderMapper.selectOrderByOrderId(orderId).getUserId();
                    //累计充值
                    int update2 = flUserMapper.addCumulativeRecharge(userId,new BigDecimal(invoice_amount2));
                    log.info(orderId+" 是否添加到累计充值中?"+(update2==1?"是":"否"));
                    //更新余额
                    int update = flUserMapper.addUserAccountByUserId(userId,new BigDecimal(invoice_amount2*PreferentialConstant.PreferentialRecharge));
                    //更新支付状态
                    int update4 = flBookorderMapper.changeStatusByOrderId(orderId,1);
                    log.info("余额订单支付状态是否修改成功？"+(update4==1?"是":"否"));
                    log.info("余额是否充值成功？"+(update2==1?"是":"否"));
                    if(update!=0)
                    {
                        //生成订单项
                        String platformNumber = orderId;
                        String payplatform = "2";
                        FlPayinfo flPayinfo = flPayinfoService.createPayInfo(userId, orderId, orderId,payplatform,platformNumber);
                    }}}
            // 如果图书支付成功 修改订单支付状态为已支付 所有已商品的库存相应减少
            // (这里逻辑是提交订单的时候库存就开始减少)
            int updated = flBookorderMapper.changeStatusByOrderId(orderId, 1);
            if (updated != 0) {
                //生成用户支付信息表 通过订单id获取用户id
                String userId = flBookorderMapper.selectOrderByOrderId(orderId).getUserId();
                //用户累计消费增加
                int update2 = flUserMapper.addCumulativeConsumption(userId,invoice_amount2);
                if(update2!=0)
                {
                    log.info(orderId+" 是否添加到消费充值中?"+(update2==1?"是":"否"));
                    //刷新用户等级
                    //获取用户累计消费金额
                    BigDecimal cumulativeConsumption = flUserMapper.selectCumulativeConsumption(userId);
                    //这里写一个工具类判断用户等级 防止重复造轮子
                    int level = OffersAndRatingsUtils.judgeTheLevel(cumulativeConsumption);
                    //然后更新等级
                    int updateLevel = flUserMapper.upLevel(userId,level);
                    log.info(" 是否添加更新了等级?"+(updateLevel==1?"是":"否"));

                }

                String platformNumber = orderId;
                FlPayinfo flPayinfo = flPayinfoService.createPayInfo(userId, userId, orderId, orderId, platformNumber);

                //返回给用户支付订单表
                if (flPayinfo != null) {
                    System.out.println("生成的订单表为：" + flPayinfo);
                }
            }

        }
        System.out.println("request:"+request.getParameter("order_id"));
        System.out.println("支付金额："+request.getParameter("qr_price"));
        System.out.println("extend:"+request.getParameter("extension"));
        Map<String, String> params = AliPayApi.toMap(request);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }

    }
}
